package com.gxa.autoparts.admin.listener;

import com.gxa.autoparts.admin.service.*;
import com.gxa.autoparts.core.pojo.*;
import com.gxa.autoparts.core.util.JsonUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.tools.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author R
 * @data 2022-01-10 14:49
 */
@Component
@Slf4j
@Transactional(rollbackFor = Throwable.class)
public class OrderListener implements ChannelAwareMessageListener {

    @Autowired
    OrderService orderService;

    @Autowired
    CouponGetService couponGetService;

    @Autowired
    CouponService couponService;

    @Autowired
    GoodsSkuService goodsSkuService;

    @Autowired
    OrderItemService orderItemService;

    @Autowired
    CouponUseRecordService couponUseRecordService;

    @Autowired
    GoodsService goodsService;

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        // 获取队列名称
        String consumerQueue = message.getMessageProperties().getConsumerQueue();
        System.out.println(consumerQueue);
        if ("sellQueue".equals(consumerQueue)){
//            try {
                // 处理消息队列接收到的信息
                Long recordId = 0L;
                Double total = 0D;
                Double skuPrice = 0D;
                String msg = message.toString();
                String[] split = msg.split("'");
                String trim = split[1].trim();
                System.out.println(11111111);
                System.out.println("trim"+trim);
                Map<String, Object> map = JsonUtil.readToObject(trim,Map.class);
                System.out.println(map);
                Long orderId = Long.parseLong(map.get("orderId").toString());
                Long userId = Long.parseLong(map.get("userId").toString());
                Long addressId = Long.parseLong(map.get("addressId").toString());
                Object skuNumber = map.get("skuWithNumber");
                List skuWithNumber = (List)skuNumber;
                Long couponId = Long.parseLong(map.get("couponId").toString());
                Double freight = Double.parseDouble(map.get("freight").toString());
                String remarks = map.get("remarks").toString();
                // 计算总价
                // 减去库存
                total += freight;
                for (Object o : skuWithNumber) {
                    Long skuId = Long.parseLong(((Map) o).get("skuId").toString());
                    Long number = Long.parseLong(((Map) o).get("number").toString());
                    GoodsSku goodsSku = goodsSkuService.selectById(skuId);
                    // 计算价格
                    total += goodsSku.getPrice()*number;
                    skuPrice += goodsSku.getPrice()*number;
                    // 修改该sku的库存和出售数量
                    goodsSku.setSaleCount(goodsSku.getSaleCount()+number);
                    goodsSku.setCount(goodsSku.getCount()-number);
                    goodsSkuService.updateById(goodsSku);
                    // 修改sku父类的出售数量
                    Goods goods = goodsService.selectById(goodsSku.getGoodsId());
                    goods.setSaleCount(goods.getSaleCount()+Integer.parseInt(number.toString()));
                    goodsService.updateById(goods);
                }

                Double shouldPay = 0D;
                shouldPay = total;
                // 查看优惠券是否使用
                if (couponId != 0L){
                    Coupon coupon = couponService.selectById(couponId);
                    String name = coupon.getName();
                    String[] result = name.split("满");
                    String s1 = result[1];
                    String[] split1 = s1.split("减");
                    String money = split1[1];
                    if (coupon.getType() == 1){
                        String[] split2 = money.split("%");
                        String s = split2[0];
                        Double cut = Double.parseDouble(s) * 0.01;
                        total = total*(1 - cut);
                    }else {
                        total -= Double.parseDouble(money);
                    }
                }
                // 新建order实体类
                Order order = new Order();
                order.setSeriaLnNumber(orderId.toString());
                order.setUserId(userId);
                order.setAddressId(addressId);
                order.setRealPrice(total);
                order.setTotalPrice(shouldPay);
                order.setState(1);
                order.setRemarks(remarks);
                order.setCreatTime(new Date());
                Order insert = orderService.insert(order);
                if (recordId != 0L){
                    CouponUseRecord couponUseRecord = couponUseRecordService.selectById(recordId);
                    couponUseRecord.setOrderId(insert.getId());
                    couponUseRecordService.updateById(couponUseRecord);
                }
                // 添加购物车商品详情订单记录
                for (Object o : skuWithNumber) {
                    Long skuId = Long.parseLong(((Map) o).get("skuId").toString());
                    Long number = Long.parseLong(((Map) o).get("number").toString());
                    OrderItem orderItem = new OrderItem();
                    orderItem.setOrderId(insert.getId());
                    orderItem.setGoodsSkuId(skuId.toString());
                    orderItem.setNumber(number);
                    orderItem.setTotalPrice(skuPrice);
                    orderItemService.insert(orderItem);
                }
                if (couponId != 0L){
                    // 添加优惠券使用记录并且修改优惠券的使用数量
                    Coupon coupon = couponService.selectById(couponId);
                    Long l = Long.parseLong(coupon.getUseCounts())+1L;
                    coupon.setUseCounts(l.toString());
                    couponService.updateById(coupon);
                    CouponUseRecord couponUseRecord = new CouponUseRecord();
                    couponUseRecord.setCouponId(couponId);
                    couponUseRecord.setOrderId(insert.getId());
                    couponUseRecordService.insert(couponUseRecord);
                    couponGetService.useCoupon(userId,couponId);
                }

            System.out.println(111111111+"sellQueue");
            System.out.println(message);
            channel.basicAck(deliveryTag,true);

//            } catch (Exception e) {
////                channel.basicAck(deliveryTag,true);
//                e.printStackTrace();
//            }
//            channel.basicAck(deliveryTag,true);
        }
        if ("dlxQueue".equals(consumerQueue)){
            String msg = message.toString();
            String[] split = msg.split("'");
            String trim = split[1].trim();
            System.out.println("-------------");
            System.out.println(trim);
            System.out.println("-------------");
            System.out.println(111111111+"dlxQueue");
            System.out.println(message);
            Long serial = Long.parseLong(trim);
            // 查询监听到的订单状态，如果是1.则表示未支付
            Order order = orderService.getStateBySerial(serial);
            Long userId = order.getUserId();
            Long orderId = order.getId();
            if (order.getState() == 1){
                // 将数据库的订单状态改为5，表示已取消
                order.setState(5);
                // 修改订单状态
                orderService.updateById(order);

                // 从优惠券使用记录通过订单id找到该订单用的优惠券id，再通过优惠券id找到领取记录表，把已使用改为未使用
                Long couponId = couponUseRecordService.getCouponIdByOrderId(orderId);
                // 删除该使用记录
                couponUseRecordService.deleteByOrderId(orderId);
                // 修改领取表的使用状态
                couponGetService.returnCoupon(userId,couponId);
                // 把优惠券的已使用总数-1
                Coupon coupon = couponService.selectById(couponId);
                Long l = Long.parseLong(coupon.getUseCounts())-1L;
                coupon.setUseCounts(l.toString());
                couponService.updateById(coupon);

                // 处理商品的库存和销售数量
                // 从item获得该订单购买的所有的skuId和商品数量
                List<Map<String, Object>> itemCount = orderItemService.getItemCount(orderId);
                for (Map<String, Object> stringLongMap : itemCount) {
                    System.out.println("-------------------------");
                    System.out.println(stringLongMap);
                    System.out.println("-------------------------");
                    // 获得skuId
                    System.out.println(stringLongMap.get("goodsSkuId"));
                    Long goodsSkuId = Long.parseLong(stringLongMap.get("goodsSkuId").toString());
                    System.out.println(goodsSkuId);
                    System.out.println("id正常-------------------------");
                    // 获得该商品数量
                    Long sum = Long.parseLong(stringLongMap.get("SUM(number)").toString());
                    System.out.println("sum正常-------------------------");
                    // 找到这个sku
                    GoodsSku goodsSku = goodsSkuService.selectById(goodsSkuId);
                    // 通过这个goodsSku找到他的goods
                    Goods goods = goodsService.selectById(goodsSku.getGoodsId());
                    // 恢复sku的库存
                    goodsSku.setCount(goodsSku.getCount()+sum);
                    // 恢复sku的销售数量
                    goodsSku.setSaleCount(goodsSku.getSaleCount()-sum);
                    // 修改该sku
                    goodsSkuService.updateById(goodsSku);
                    // 恢复goods的销售数量
                    goods.setSaleCount(goods.getSaleCount()-Integer.parseInt(sum.toString()));
                    // 修改该goods
                    goodsService.updateById(goods);
                }
                // 删除订单商品详情记录
                orderItemService.deleteOrderItem(orderId);

            }
            channel.basicAck(deliveryTag,true);
        }
    }

}
